package com.egdigital.allzic.ui.fragment;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCacheManager;
import com.egdigital.allzic.data.object.Category;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.ui.activity.ActivityMain;
import com.egdigital.allzic.ui.adapter.AdapterCategory;
import com.egdigital.allzic.ui.adapter.AdapterListRadio;
import com.egdigital.allzic.utils.Utils;

public class FragmentTabFavorite extends SherlockFragment implements OnClickListener, OnItemLongClickListener, OnItemClickListener {

	private static final String	TAG					= FragmentTabFavorite.class.getSimpleName();	// log
	private List<Station>		mListStations;
	private List<Category>		mListCategory;
	private boolean				isStationSelected	= true;
	protected ActivityMain		mParent;
	//
	private View				mView;
	private View				mNoFavoriteView;
	private TextView			mStationButton;
	private TextView			mCategoryButton;
	private ListView			mListView;
	private AdapterCategory		mCategoryAdapter;
	private AdapterListRadio	mStationAdapter;
	private BroadcastReceiver	mMessageReceiver	= new BroadcastReceiver() {

														@Override
														public void onReceive(Context context, Intent intent) {
															if (intent.getExtras().getBoolean("isStation")) {
																mListStations = JsonCacheManager.getStations(mParent.getApplicationContext(), JsonCacheManager.FAVORITE_STATION);
																updateStationAdapter();
															} else {
																mListCategory = JsonCacheManager.getCategories(mParent.getApplicationContext());
																updateCategoryAdapter();
															}
														}
													};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_tab_favorite, container, false);
		mStationButton = (TextView) mView.findViewById(R.id.fragment_favorite_station);
		mCategoryButton = (TextView) mView.findViewById(R.id.fragment_favorite_category);
		mListView = (ListView) mView.findViewById(R.id.fragment_favorite_list);
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		mStationButton.setOnClickListener(this);
		mCategoryButton.setOnClickListener(this);
		mListView.setOnItemLongClickListener(this);
		mListView.setOnItemClickListener(this);
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.fragment_favorite_station:
				updateStationAdapter();
				break;
			case R.id.fragment_favorite_category:
				updateCategoryAdapter();
				break;
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mParent = (ActivityMain) activity;
		LocalBroadcastManager.getInstance(mParent.getApplicationContext()).registerReceiver(mMessageReceiver, new IntentFilter("fav_modification"));
	}

	@Override
	public void onDetach() {
		LocalBroadcastManager.getInstance(mParent.getApplicationContext()).unregisterReceiver(mMessageReceiver);
		mParent = null;
		super.onDetach();
	}

	@Override
	public void onResume() {
		// category
		if (!isStationSelected) {
			mListCategory = JsonCacheManager.getCategories(mParent.getApplicationContext());
			if (mListCategory == null || mListCategory.isEmpty()) {
				setNoResultUI();
			} else {
				setResultUI();
				if (mCategoryAdapter == null) {
					mCategoryAdapter = new AdapterCategory(mParent.getApplicationContext(), mListCategory);
					mListView.setAdapter(mCategoryAdapter);
				} else {
					mCategoryAdapter.setData(mListCategory);
					mCategoryAdapter.notifyDataSetChanged();
				}
			}
		} else {
			// station
			mListStations = JsonCacheManager.getStations(mParent.getApplicationContext(), JsonCacheManager.FAVORITE_STATION);
			if (mListStations == null || mListStations.isEmpty()) {
				setNoResultUI();
			} else {
				setResultUI();
				if (mStationAdapter == null) {
					mStationAdapter = new AdapterListRadio(mParent.getApplicationContext(), mListStations, R.layout.cell_list_radio);
					mListView.setAdapter(mStationAdapter);
				} else {
					mStationAdapter.setData(mListStations);
					mStationAdapter.notifyDataSetChanged();
				}
			}
		}
		super.onResume();
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
		try {
			if (isStationSelected) {
				mListStations = JsonCacheManager.removeStation(mParent.getApplicationContext(), position, JsonCacheManager.FAVORITE_STATION);
				if (mListStations == null || mListStations.isEmpty()) {
					setNoResultUI();
				} else {
					setResultUI();
					mStationAdapter.setData(mListStations);
					mStationAdapter.notifyDataSetChanged();
				}
				Utils.customToast(new SpannableStringBuilder(getString(R.string.favorite_station_removed)), mParent.getApplicationContext(), false);
				mParent.updatePlayerBanner();
			} else {
				mListCategory = JsonCacheManager.removeCategory(mParent.getApplicationContext(), position);
				if (mListCategory == null || mListCategory.isEmpty()) {
					setNoResultUI();
				} else {
					setResultUI();
					mCategoryAdapter.setData(mListCategory);
					mCategoryAdapter.notifyDataSetChanged();
				}
				Utils.customToast(new SpannableStringBuilder(getString(R.string.favorite_category_removed)), mParent.getApplicationContext(), false);
			}
		} catch (IOException e) {
		}
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		if (isStationSelected) {
			// disableList();
			Station station = mListStations.get(position);
			mParent.prepareToPlay(station);
			mParent.showPlayerBanner();
			mParent.updatePlayerBanner();
		} else {
			FragmentCategoryRadio fragment = new FragmentCategoryRadio();
			Bundle param = new Bundle();
			param.putParcelable("category", mListCategory.get(position));
			fragment.setArguments(param);
			mParent.getSupportFragmentManager()
					.beginTransaction()
					.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
					.add(R.id.fragment_category, fragment)
					.addToBackStack("" + ActivityMain.INDEX_CATEGORY)
					.commit();
			mParent.mPager.setCurrentItem(1); // change tab
		}
	}

	/**
	 * methods
	 */
	private void setNoResultUI() {
		if (mNoFavoriteView == null) {
			ViewStub stub = (ViewStub) mView.findViewById(R.id.fragment_favorite_stubnofavorite);
			mNoFavoriteView = stub.inflate();
		} else {
			mNoFavoriteView.setVisibility(View.VISIBLE);
		}
		TextView text_1 = (TextView) mNoFavoriteView.findViewById(R.id.text_1);
		if (isStationSelected) {
			text_1.setText(getString(R.string.no_favorite_radio));
		} else {
			text_1.setText(getString(R.string.no_favorite_category));
		}
		mListView.setVisibility(View.GONE);
	}

	private void setResultUI() {
		if (mNoFavoriteView != null) {
			mNoFavoriteView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		}
	}

	private void updateStationAdapter() {
		isStationSelected = true;
		if (mListStations == null || mListStations.isEmpty()) {
			setNoResultUI();
		} else {
			setResultUI();
			if (mStationAdapter == null) {
				mStationAdapter = new AdapterListRadio(mParent.getApplicationContext(), mListStations, R.layout.cell_list_radio);
				mListView.setAdapter(mStationAdapter);
			} else {
				mStationAdapter.setData(mListStations);
				mListView.setAdapter(mStationAdapter);
			}
		}
		mStationButton.setBackgroundResource(R.drawable.selector_blue_favorite_dark);
		mCategoryButton.setBackgroundResource(R.drawable.selector_blue_favorite);
	}

	private void updateCategoryAdapter() {
		isStationSelected = false;
		if (mListCategory == null || mListCategory.isEmpty()) {
			setNoResultUI();
		} else {
			setResultUI();
			if (mCategoryAdapter == null) {
				mCategoryAdapter = new AdapterCategory(mParent.getApplicationContext(), mListCategory);
				mListView.setAdapter(mCategoryAdapter);
			} else {
				mCategoryAdapter.setData(mListCategory);
				mListView.setAdapter(mCategoryAdapter);
			}
		}
		mStationButton.setBackgroundResource(R.drawable.selector_blue_favorite);
		mCategoryButton.setBackgroundResource(R.drawable.selector_blue_favorite_dark);
	}
}
